import type { ResultLogin,ResultGoodsList,ResultGoodsDetail } from '../config/data/result'
import { baseUrl, jsonHeader, uploadFileHeader } from '../config/constant/index'

//返回结果
export interface Result<T> {
  code: number //响应状态码
  msg: string //响应信息
  data: T //响应数据
}


const api = {

  //登录
  login: (code: string): Promise<Result<ResultLogin>> => {
    return new Promise((reslove, reject) => {
      uni.request({
        url: baseUrl + '/attestation/login?authType=WxLogin',
        method: 'POST',
        data: {openid:code},
        header: jsonHeader,
        success: (res) => {
                    //存入令牌
          uni.setStorage({
            key: 'Authorization-token',
            data: res.data.data.access_tokens
          });
          reslove(res.data)

        },
        fail: (err) => {
          reject(err)
        },
      })
    })
  },


  //分页获取商品列表
  commodityPaginatedQueries:(page:Number=1,size:Number=8,commodityTypeName:string=''):Promise<Result<ResultGoodsList[]>>=>{

     return new Promise((reslove,reject)=>{
          uni.request({
            url:baseUrl+`/commodity/queryPage?page=${page}&size=${size}&commodityTypeName=${commodityTypeName}`,
            methods:'POST',
            header:jsonHeader,
            data:{
              'page':page,
              'size':size,
              'commodityTypeName':commodityTypeName
            },
            success:(res)=> {
                reslove(res.data)
            },
            error:(err:any)=>{
              reject(err)
            }
          })
     })
  },

  //商品详情内容
  commodityDetail:(id:string):Promise<Result<ResultGoodsDetail>>=>{
      return new Promise((reslove,reject)=>{
         uni.request({
          url: `${baseUrl}/commodity/${id}`,
          header: jsonHeader,
          method: 'GET',
          success: (res) => {
            reslove(res.data)
          },
          fail: (err) => {
            reject(err)
          }
         })
      })
  },
  
  //添加购物车
  cartAdd:():Promise<Result<Number>>=>{
    return new Promise((reslove,reject)=>{
       uni.request({
        url: `${baseUrl}`,
        data: {},
        header: jsonHeader,
        method: 'POST',
        success: (res) => {
          reslove(res.data)
        },
        fail: (error) => {
          reject(error)
        }
       })
    })
  },

  methodB: (code: string[]) => code.map((str) => String(str.length)),
}

export { api }
